import React, {Component,Fragment} from 'react';
import './index.css'

const MyContext=React.createContext()
const {Provider} =MyContext
class A extends Component {
    state={username:'Tom'}
    render() {
        return (
            <div className="parent">
                <h2>A组件</h2>
                <h2>{this.state.username}</h2>
                {/*<B username={this.state.username}/>*/}
                <Provider value={this.state.username}>
                    <B />
                </Provider>

            </div>
        );
    }
}

export default A;
class B extends Component {
    render() {
        return (
            <div className="child">
                <h2>B</h2>
                <h3>从A接收到的用户名</h3>
                <C/>
            </div>
        );
    }
}
//类式组件
// class C extends Component {
//     //声明接收MyContext的值
//     static contextType =MyContext
//     render() {
//         console.log(this.context)
//         return (
//             <div className="grand">
//                 <div>
//                     <h2>C</h2>
//                     <h3>C从A接收到的用户名：{this.context}</h3>
//                 </div>
//             </div>
//         );
//     }
// }

//函数式组件
function C (){
    return(
        <div className="grand">
            <h2>C</h2>
            <h2>C从A接收到的用户名</h2>
            <MyContext.Consumer>
                {value => {
                    return <span>{value}</span>
                }}
            </MyContext.Consumer>
        </div>
    )
}